package com.glsc.ngateway.opmanage.service.deposit;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryBank;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.deposit.DepositoryBankRepository;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class DepositoryBankService {


    @Resource
    private DepositoryBankRepository depositoryBankRepository;

    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<DepositoryBank> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<DepositoryBank> page = depositoryBankRepository.findAll(SpecificationUtil.buildSpecification(param, DepositoryBank.class), pageable);

        return page;
    }

    /**
     * 查询所有生效状态的存管银行信息
     *
     * @return
     */
    public List<DepositoryBank> listAll() {
        List<DepositoryBank> banks = depositoryBankRepository.findAll(Example.of(DepositoryBank.builder().deleted("N").build()));
        return banks;
    }


    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public DepositoryBank findById(Integer id) {
        Optional<DepositoryBank> optional = depositoryBankRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据名称查找银行信息
     *
     * @param bankName
     * @return
     */
    public DepositoryBank findByName(String bankName) {
        List<DepositoryBank> banks = depositoryBankRepository.findAll(Example.of(DepositoryBank.builder().bankName(bankName).build()));
        if (CollectionUtil.isNotEmpty(banks)) {
            return banks.get(0);
        }
        return null;
    }

    /**
     * 保存
     *
     * @param bank
     * @return
     */
    public DepositoryBank save(DepositoryBank bank) {
        return depositoryBankRepository.save(bank);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        depositoryBankRepository.deleteById(id);
    }


}
